package com.army.study.util;

import com.army.study.ResourceTable;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.media.image.ImagePacker;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.Size;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 分布式文件工具类
 */
public class DistributedFileUtil {
    // 上下文
    private final Context mContext;

    /**
     * 构造方法
     * @param context
     */
    public DistributedFileUtil(Context context) {
        this.mContext = context;
    }

    /**
     * 写信件
     * @param fileName
     * @param letterContent
     * @return
     */
    public PixelMap writeLetter(String fileName, String letterContent) {
        // 获取分布式文件路径
        String filePath = mContext.getDistributedDir() + File.separator + fileName + ".jpg";
        Texture texture=null;
        try {
            // 从资源文件获取信纸背景图片
            InputStream inputStream = mContext.getResourceManager().getResource(ResourceTable.Media_bg);
            ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
            srcOpts.formatHint = "image/jpeg";
            ImageSource imageSource = ImageSource.create(inputStream, srcOpts);
            // 设置图片参数
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            decodingOptions.desiredSize=new Size(720,1080);
            PixelMap pixelMap = imageSource.createPixelmap(decodingOptions);
            //用于保存画图结果
            texture=new Texture(pixelMap);
            Canvas canvas=new Canvas(texture);
            Paint paint=new Paint();
            paint.setTextSize(50);
            paint.setStrokeWidth(8);
            paint.setColor(Color.BLACK);
            // 把内容写到信纸上
            canvas.drawChars(paint,letterContent.toCharArray(),50,140);
            // 文件输出流
            FileOutputStream fos=new FileOutputStream(filePath);

            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            packingOptions.format = "image/jpeg";//只支持image/jpeg
            packingOptions.quality = 90;
            boolean result = imagePacker.initializePacking(fos, packingOptions);
            if(result)
            {
                //这里获取绘画后的pixelMap用来保存
                result = imagePacker.addImage(texture.getPixelMap());
                if (result) {
                    long dataSize = imagePacker.finalizePacking();
                    System.out.println("文件大小："+dataSize);
                    ToastUtil.getInstance().showToast(mContext, "创建成功！");
                }
            }

            fos.flush();
            fos.close();
        } catch (IOException | NotExistException e) {
            System.out.println("文件保存出错："+e.getMessage());
            e.printStackTrace();
        }
        
        return texture.getPixelMap();
    }

    /**
     * 读取信件
     * @param fileName
     * @param letterContent
     * @return
     */
    public PixelMap readImage(String fileName, String letterContent) {
        // 获取分布式文件路径
        String filePath = mContext.getDistributedDir() + File.separator + fileName;
        // 根据分布式文件路径,生成文件
        File file = new File(filePath);
        if (!file.exists()) {
            // 如果文件不存在, 调用写信件
            writeLetter(fileName, letterContent);
        }
        // 图片参数
        ImageSource.SourceOptions srcOpts = new ImageSource.SourceOptions();
        srcOpts.formatHint = "image/jpeg";
        // 创建图片源
        ImageSource imageSource = ImageSource.create(file, srcOpts);
        // 生成图片
        PixelMap pixelMap = imageSource.createPixelmap(null);

        return pixelMap;
    }

    /**
     * 获取文件列表
     * @return
     */
    public List<String> getFileList() {
        // 获取分布式文件列表
        File[] files = mContext.getDistributedDir().listFiles();
        List<File> listFile = new ArrayList<>(Arrays.asList(files));
        // 排序文件顺序
        listFile.sort((file, newFile) -> {
            if (file.lastModified() > newFile.lastModified()) {
                return -1;
            } else if (file.lastModified() == newFile.lastModified()) {
                return 0;
            } else {
                return 1;
            }
        });
        List<String> listFileName = new ArrayList<>();
        // 获取文件列表文件名
        for (File f : listFile) {
            if (f.isFile()) {
                String name = f.getName();
                listFileName.add(name);
            }
        }
        return listFileName;
    }
}
